package com.laker.autotest.api.core;

import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;

public class EasyOkHttpClient {


    private static final MediaType JSON = MediaType.get("application/json");

    private final OkHttpClient client;

    private final String baseUri;

    public EasyOkHttpClient(OkHttpClient client, String baseUri) {
        this.client = client;
        this.baseUri = baseUri;
    }


    /**
     * 发送 GET 请求
     */
    @SneakyThrows
    public Response get(String url) {
        Request request = new Request.Builder()
                .url(baseUri + url)
                .get()
                .build();
        return execute(request);
    }

    /**
     * 发送 POST JSON 请求
     */
    @SneakyThrows
    public Response postJson(String url, Object body) {
        String jsonBody = JSONUtil.toJsonStr(body);
        RequestBody requestBody = RequestBody.create(jsonBody, JSON);

        Request request = new Request.Builder()
                .url(baseUri + url)
                .post(requestBody)
                .addHeader("Content-Type", "application/json")
                .build();

        return execute(request);
    }

    /**
     * 发送 PUT JSON 请求
     */
    @SneakyThrows
    public Response putJson(String url, Object body) {
        String jsonBody = JSONUtil.toJsonStr(body);
        RequestBody requestBody = RequestBody.create(jsonBody, JSON);

        Request request = new Request.Builder()
                .url(baseUri + url)
                .put(requestBody)
                .addHeader("Content-Type", "application/json")
                .build();

        return execute(request);
    }

    /**
     * 发送 DELETE 请求
     */
    public Response delete(String url) {
        Request request = new Request.Builder()
                .url(baseUri + url)
                .delete()
                .build();

        return execute(request);
    }

    @SneakyThrows
    private @NotNull Response execute(Request request) {
        return client.newCall(request).execute();
    }

    /**
     * 将 Response Body 解析为指定类型对象（使用 Gson）
     */
    @SneakyThrows
    public static <T> T parseResponse(Response response, Class<T> clazz) {
        if (response == null || !response.isSuccessful() || response.body() == null) {
            throw new IOException("Invalid response or empty body");
        }
        return JSONUtil.parse(response.body().charStream()).toBean(clazz);
    }

    /**
     * 同步发送请求并返回反序列化后的结果
     */
    @SneakyThrows
    public <T> T execute(Request request, Class<T> clazz) {
        try (Response response = execute(request)) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return parseResponse(response, clazz);
        }
    }
}